import { defineStore } from 'pinia'
import { BookInfo } from './state'
import bookApi from '@/api/bookApi'
import { AxiosResponse } from 'axios'
import storage from '@/utils/goodStorageUtil'
import searchStore from '@/piniastore/search/index'

export default defineStore('bookStore', {
  state: () => {
    return initState
  },
  getters: {
    getAutoCompKeyword() {
      return searchStore().getAutoCompKeyword
    },
    findBookList(state) {
      return state.bookList
    },
    getOperate(state) {
      return state.operate || storage.get('operate')
    },
    getPublisherList(state) {
      return state.publisherList
    },
  },
  actions: {
    storeOperate(operate: Operate) {
      this.operate = operate
      storage.set('operate', operate)
    },
    async findBooksByThirdCtgyId(thirdCtgyid: number, page: number, size: number) {
      const bookList: AxiosResponse<BookInfo[]> = await bookApi.findBookList(thirdCtgyid, page, size)
      this.bookList = bookList.data
    },
    async findBooksByAutoCompKeyword(autoCompKeyWord: string) {
      const bookList: AxiosResponse<BookInfo[]> = await bookApi.findBooksByAutoCompKeyword(autoCompKeyWord)
      this.bookList = bookList.data
      storage.set('bookList', bookList.data)
    },
    async findPublishersByAutoCompKey() {
      const publisherList: AxiosResponse<Publisher[]> = await bookApi.findPublishersByAutoCompKey(this.getAutoCompKeyword.keyword)
      this.publisherList = publisherList.data
      console.log('this.publisherList',this.publisherList)
    },
    async findBksByPublishIds(publishIds: number[]) {
      const bookList: AxiosResponse<BookInfo[]> = await bookApi.findBksByPublishIds(publishIds)
      console.log('this.bookList',this.bookList)
      this.bookList = bookList.data
    },
  },
})

export enum Operate {
  INIT = 0,
  THRDCTGYID = -1,
  AUTOCOMPKEYWORD = 2,
}

type InitStateType = {
  bookList: BookInfo[]
  operate: Operate
  publisherList: Publisher[]
}

const initState: InitStateType = {
  bookList: [],
  operate: Operate.INIT,
  publisherList: [],
}

interface Publisher {
  publishid: number
  publishername: string
}
